package com.huarun.shiro;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.util.StringUtil;
import com.huarun.common.ResponseMessage;
import com.huarun.common.util.IOUtils;
import com.huarun.common.util.ResultCodeEnum;
import com.huarun.common.util.ResultCodeValue;
import com.huarun.module.sys.util.UserInfoUtil;
import com.huarun.redis.RedisKeyPrefix;
import com.huarun.redis.RedisUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * 
 * @author hqy
 * @创建时间   2018-10-24 19:29
 * @Description 针对小程序url参数判断
 */
public class UrlValidateFilter extends PathMatchingFilter {
	private Logger logger = LoggerFactory.getLogger(UrlValidateFilter.class);
	@Resource
	private RedisUtils redis=null;

	@Override
	protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
//		String openId = request.getParameter("openId");
//		String accountNo = request.getParameter("accountNo");
//		if (StringUtils.isBlank(openId)) {
//			throw new MyException(ResultCodeValue.R_PARAM_ERROR, "openId不能为空");
//		}
//		//		if (StringUtils.isBlank(accountNo)) {
//		//			throw new MyException(ResultCodeValue.R_PARAM_ERROR, "手机号不能为空");
//		//		}
//		if (redis == null) {
//			redis = SpringUtils.getBean(RedisUtils.class);
//		}
//		/**智慧运营管理平台是否登入标识*/
//		String token = request.getParameter("token");
//		/**face++是否登入标识*/
//		String cookie = request.getParameter("cookie");
//		/**只要有一个标识不为空，则判断该用户已登入*/
//		if (!StringUtils.isBlank(token) && !StringUtils.isBlank(cookie)) {
//			Map<String, Object> map = new HashMap<String, Object>();
//			/**请求face++或者智慧运营管理平台得到cookie或token*/
//			map.put("appkey", Constant.MANAGE_APPKEY);
//			map.put("secret", Constant.MANAGE_SECRET);
//			try {
//				//token = HttpUtil.doGet(Constant.MANAGE_GETTOKEN, map);
//				//判断token或者cookie
//				//开始绑定小程序和手机号
//				redis.set(accountNo, openId);
//			} catch (Exception e) {
//				e.printStackTrace();
//				return false;
//			}
//		}
//		if (!openId.equals(redis.get(openId))) {
//			throw new MyException(ResultCodeValue.R_OPENID_NOT_FOUND, "请求的openId在系统中找不到");
//		}
		logger.info("=======WXUrlValidateFilte=======");
		/**是否从智慧运营管理平台请求过来标识*/
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		httpServletResponse.setCharacterEncoding("UTF-8");
		httpServletResponse.setContentType("application/json; charset=utf-8");
		if ("OPTIONS".equals(httpServletRequest.getMethod())) {
			httpServletResponse.setStatus(200);
			return true;
		}
		// /huarun/wx/newVisitorApply/getCheckCode
		String requestURL = httpServletRequest.getRequestURI();
		if("/huarun/wx/newVisitorApply/getCheckCode".equals(requestURL)
				|| "/huarun/wx/newVisitorApply/getMeCode".equals(requestURL)){
			return true;
		}
		String openId = httpServletRequest.getHeader("openId");
		String sKey = httpServletRequest.getHeader("sKey");

		String isLogin = httpServletRequest.getHeader("isLogin");
		//2019.9.12 访客分支，有openId无sKey，允许往后走  isLogin 0未登录
		//2019.11.29 前端传值isLogin判断前端的登录态，如果为已登录，则继续判断后台的逻辑
		if (StringUtil.isEmpty(sKey) && openId != null && !"1".equals(isLogin)) {
			return true;
		}
//		if (sKey == null || openId == null) {
//			throw new MyException(ResultCodeValue.R_SESSION_KEY_IS_NULL, "请求的skey或openId为空，请重新获取用户数据");
//		}
		try {

			String sKeyValue = UserInfoUtil.getRedisInfo(RedisKeyPrefix.USER_TOKEN, openId);
			String userInfo = UserInfoUtil.getRedisInfo(RedisKeyPrefix.USER_INFO, openId);

			System.out.println(httpServletRequest.getRequestURL());
			if (null != sKeyValue && null != userInfo) {
				ResponseMessage<String> respon = UserInfoUtil.checkUserRole(httpServletRequest);
				if (respon.getCode() == ResultCodeEnum.SUCCESS.code) {
					return true;
				} else {
					writerResponse(httpServletResponse, respon);
					return false;
				}

			} else {
				System.out.println("token失效" + ResultCodeValue.R_TOKEN_IS_NULL);
				ResponseMessage<String> respon = new ResponseMessage<>();
				respon.setCodeAndMsg(ResultCodeValue.R_TOKEN_IS_NULL, "登录态过期，请重新登录");
				//				httpServletResponse.setStatus(ResultCodeValue.R_TOKEN_IS_NULL);
				writerResponse(httpServletResponse, respon);
				return false;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("UrlValidateFilter解析失败:" + e.getMessage());

		}

		/**从SecurityUtils里边创建一个 subject*/
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		session.setAttribute("openId", openId);
		session.setAttribute("sKey", sKey);
		return true;

	}

	public void writerResponse(HttpServletResponse response, ResponseMessage<String> resultInfo) {
		PrintWriter writer = null;
		OutputStreamWriter osw = null;
		String str = null;
		try {
			osw = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
			writer = new PrintWriter(osw, true);
			str = JSON.toJSONString(resultInfo);
			writer.write(str);
			writer.flush();
			writer.close();
			osw.close();
		} catch (UnsupportedEncodingException e) {
			logger.error("IEMSTokenInterceptor:拦截器返回信息失败:" + e.getMessage(), e);
		} catch (IOException e) {
			logger.error("IEMSTokenInterceptor:拦截器返回信息失败:" + e.getMessage(), e);
		} finally {
			if (null != writer) {
				writer.close();
			}
			if (null != osw) {
				try {
					osw.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			IOUtils.closeStream(writer, osw);
		}
	}

}
